<?php

namespace App\Http\Controllers\Seller;

use App\Events\OrderEvent;
use App\Library\Mall\Seller\SoldManagers;
use App\WeChat\Message\TemplateMessage;
use App\WeChat\WechatDefaultConfig;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;

class SoldController extends BaseController
{
    use SoldManagers, WechatDefaultConfig;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->assign(['sideMenu' => 'sold']);
    }

    /**
     * 已卖出的宝贝
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {

        $this->assign([
            'tab' => 'all',
            'order_no' => '',
            'buyer_name' => '',
            'pay_type' => '',
            'title' => '',
            'time_begin' => '',
            'time_end' => '',
            'wuliu_state' => ''
        ]);

        $queryParams = [];
        $query = $this->user()->solds()->with('items')->where('seller_deleted', 0);
        $tab = $request->get('tab', 'all');
        if ($tab) {
            $queryParams['tab'] = $tab;
            if ($tab == 'waitPay') {
                $query = $query->where('order_state', 1);
            } elseif ($tab == 'waitSend') {
                $query = $query->where('order_state', 2);
            } elseif ($tab == 'send') {
                $query = $query->where('order_state', 3);
            } elseif ($tab == 'waitRate') {
                $query = $query->where('order_state', 4)->where('buyer_rate', 0);
            } elseif ($tab == 'refunding') {
                $query = $query->where('order_state', 5);
            } elseif ($tab == 'closed') {
                $query = $query->where('order_state', 6);
            }
        }

        $order_no = $request->get('order_no');
        if ($order_no) {
            $queryParams['order_no'] = $order_no;
            $query = $query->where('order_no', $order_no);
        }

        $buyer_name = $request->get('buyer_name');
        if ($buyer_name) {
            $queryParams['buyer_name'] = $buyer_name;
            $query = $query->where('buyer_name', 'LIKE', "%$buyer_name%");
        }

        $pay_type = $request->get('pay_type', 0);
        if ($pay_type) {
            $queryParams['pay_type'] = $pay_type;
            $query = $query->where('pay_type', $pay_type);
        }

        $wuliu_state = $request->get('wuliu_state', 0);
        if ($wuliu_state) {
            $queryParams['wuliu_state'] = $wuliu_state;
            switch ($wuliu_state) {
                case 1:
                    $query = $query->where('shipping_state', 0);
                    break;
                case 2:
                    $query = $query->where('shipping_state', 1);
                    break;
                case 3:
                    $query = $query->where('shipping_state', 1)->where('receive_state', 1);
                    break;
                default:
                    ;
            }
        }

        $title = $request->get('title');
        if ($title) {
            $queryParams['title'] = $title;
            $query = $query->whereHas('items', function (Builder $builder) use ($title) {
                return $builder->where('title', 'LIKE', "%$title%");
            });
        }

        $time_begin = $request->get('time_begin');
        if ($time_begin) {
            $queryParams['time_begin'] = $time_begin;
            $query = $query->where('created_at', '>', strtotime($time_begin));
        }

        $time_end = $request->get('time_end');
        if ($time_end) {
            $queryParams['time_end'] = $time_end;
            $query = $query->where('created_at', '<', strtotime($time_end));
        }
        $this->assign($queryParams);

        $orders = $query->orderByDesc('order_id')->paginate(10);
        return $this->view('seller.sold.index', [
            'orders' => $orders,
            'pagination' => $orders->appends($queryParams)->render()
        ]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function refund(Request $request)
    {
        $order_id = $request->input('order_id');
        $order = $this->user()->solds()->find($order_id);
        $refund = $order->refund()->with('express')->first();
        $refund->images = unserialize($refund->images);
        if (!is_array($refund->images)) {
            $refund->images = [];
        }

        return $this->view('seller.trade.refund', compact('order', 'refund'));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function checkRefund(Request $request)
    {

        $refund_status = $request->input('refund_status', 1);
        $seller_message = $request->input('seller_message', '');

        $order_id = $request->input('order_id');
        $order = $this->user()->solds()->find($order_id);
        $refund = $order->refund;
        $refund->seller_message = $seller_message;
        //同意退款
        if ($refund_status == 1) {
            $refund->refund_status = 1;
            $refund->refund_at = time();

            $trade = $order->trade;
            if ($trade) {
                $res = $this->payment()->refund->byOutTradeNumber(
                    $trade->out_trade_no,
                    $refund->refund_no,
                    1,
                    1
                );
                //dd($res);
//                $res = $this->payment()->refund->byOutTradeNumber(
//                    $trade->out_trade_no,
//                    $refund->refund_no,
//                    intval($trade->total_amount*100),
//                    intval($refund->refund_amount)
//                );
            }
            $order->changeToRefunded();
            $refund->save();

            event(new OrderEvent($order, 'refunded'));
        }

        if ($refund_status == 2) {
            $refund->refund_status = 2;
            $refund->refund_at = time();
            $refund->save();

//            if ($order->pay_status){
//                $order->trade_status = 2;
//            }
//
//            if ($order->shipping_status)
//            {
//                $order->trade_status = 3;
//            }
//
//            if ($order->receive_status)
//            {
//                $order->trade_status = 4;
//            }
//            $order->save();
            $message = new TemplateMessage();
            $message->setTemplateId('rIC7TLRSePfQnhSl9wipe0C3Uu73mNLs9DKkBPYvZ8E');
            $message->setFirst('退款失败通知');
            $message->setDataValue('keyword1', $order->order_no);
            $message->setDataValue('keyword2', $refund->refund_amount);
            $message->setRemark('您的退款申请失败，' . $seller_message);
            $order->buyer->sendTemplateMessage($message);
        }

        return $this->messager()->setMessage('退款已处理')->render();
    }

    public function export(Request $request)
    {
        $data = [
            [
                '订单号',
                '宝贝',
                '单价',
                '数量',
                '买家',
                '交易状态',
                '实收款',
                '交易时间'
            ]
        ];

        $trade_status_items = __('order.seller_trade_states');
        $orders = $this->user()->solds()->with('items')->orderByDesc('order_id')->limit(1000)->get();
        foreach ($orders as $order) {
            foreach ($order->items as $item) {
                $data[] = [
                    $order->order_no,
                    $item->title,
                    $item->price,
                    $item->quantity,
                    $order->buyer_name,
                    $trade_status_items[$order->trade_status],
                    $item->total_fee,
                    @date('Y-m-d H:i:s', $order->created_at)
                ];
            }
        }

        return collect($data)->downloadExcel(
            'orders.xls',
            'Xls',
            false
        );
    }
}
